#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from Utils.Logger import Logger
from Src.Public.PublicData import hostDataDict
from Config.GlobalVariables import SSH_CONNECT_TIMEOUT, SSH_CONNECT_ATTEMPTS, SSH_RECONNECT_FREQUENCY
from datetime import datetime
import paramiko
import time


class SSHRemote:
    """通过SSH远程连接测试服务器"""
    logger = Logger().get_logger()

    def __init__(self, host_ip=hostDataDict['HostIp'], ssh_port=hostDataDict['SSHPort'], username=hostDataDict['SSHUsername'],
                 password=hostDataDict['SSHPassword'], timeout=SSH_CONNECT_TIMEOUT):
        self.host_ip = host_ip
        self.ssh_port = ssh_port
        self.ssh_username = username
        self.ssh_password = password
        self.timeout = timeout
        self.__try_times = SSH_CONNECT_ATTEMPTS
        self.__max_times = self.__try_times
        self.ssh_client = None

    def connect(self):
        while True:
            try:
                self.logger.debug('尝试远程连接服务器 [hostIp:{0}]'.format(self.host_ip))
                self.ssh_client = paramiko.SSHClient()
                self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                self.ssh_client.connect(self.host_ip, self.ssh_port, self.ssh_username, self.ssh_password, timeout=self.timeout)
            except Exception as e:
                if self.__try_times != 0:
                    self.logger.debug('远程连接服务器失败，尝试重连 [hostIp:{0}]，{1}'.format(self.host_ip, str(e)[:-1]))
                    self.__try_times -= 1
                    time.sleep(SSH_RECONNECT_FREQUENCY)
                else:
                    self.logger.error('连续{0}次远程连接服务器失败 [hostIp:{1}], {2}'.format(self.__max_times, self.host_ip, str(e)[:-1]))
                    return False
            else:
                self.logger.debug('远程连接服务器成功 [hostIp:{0}]'.format(self.host_ip))
                return True

    def close(self):
        self.ssh_client.close()
        self.logger.debug('终止连接远程服务器 [hostIp:{0}]'.format(self.host_ip))

    def exec_cmd(self, cmd):
        try:
            _ssh_stdin, _ssh_stdout, _ssh_stderr = self.ssh_client.exec_command(cmd, timeout=self.timeout)
            ssh_stdout = _ssh_stdout.readlines()
            ssh_stderr = _ssh_stderr.readlines()
            if ssh_stdout and not ssh_stderr:
                self.logger.debug('远程服务器执行命令成功 [hostIp:{0}] [cmd:{1}]'.format(self.host_ip, cmd))
                return ssh_stdout
            elif ssh_stderr and not ssh_stdout:
                self.logger.debug('远程服务器执行命令失败 [hostIp:{0}] [cmd:{1}] [reason:{2}]'.format(self.host_ip, cmd, ssh_stderr))
                return ssh_stderr
        except Exception as e:
            self.logger.error('远程服务器执行命令失败 [hostIp:{0}] [cmd:{1}] [reason:{2}]'.format(self.host_ip, cmd, str(e)[:-1]))
            return None

    @staticmethod
    def convert_remote_server_datetime(string_datetime):
        string_datetime = string_datetime[0].rstrip()
        index = string_datetime.find('星期')
        _current_datetime = str(string_datetime[:index - 1] + string_datetime[index + 3: -4].replace(' ', ''))
        date_time = datetime.strptime(_current_datetime, '%Y年%m月%d日%H:%M:%S')
        return date_time

    def get_remote_server_current_datetime(self):
        current_datetime = self.exec_cmd('date')
        date_time = SSHRemote.convert_remote_server_datetime(current_datetime)
        return date_time


if __name__ == '__main__':
    pass
